package com.heeexy.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.util.CommonUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.*;


@RestController
@RequestMapping("/tle_upload")
public class TleUploadController {
    @PostMapping("/upload")
    public JSONObject upload(@RequestBody MultipartFile file) throws Exception {

        System.out.println(file.getOriginalFilename());
        String encoding = "UTF-8";
        InputStreamReader read = new InputStreamReader(file.getInputStream(), encoding);
        BufferedReader bufferedReader = new BufferedReader(read);
        String name = null;
        String line1 = null;
        String line2 = null;
        String tle = null;
        while((name = bufferedReader.readLine()) != null){
            line1 = bufferedReader.readLine();
            line2 = bufferedReader.readLine();
            tle = name + "\n" + line1 + "\n" + line2;
            System.out.println(tle);
            insertTle(name, tle);
        }
        return CommonUtil.successJson();
    }

    private void insertTle(String tleName, String tleData){
        Connection c = null;
        PreparedStatement stmt = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:/home/wbc/Desktop/space_java/space_debris/web_ui/debriswatch-v0.2.1_20190628/sat_0815.db");
            c.setAutoCommit(false);
            System.out.println("Opened database successfully");

            String sql = "insert into sat_tle (name, tle) values (?, ?);";
            stmt = c.prepareStatement(sql);
            stmt.setString(1, tleName);
            stmt.setString(2, tleData);
            stmt.execute();
            c.commit();
            stmt.close();
            c.close();
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            System.exit(0);
        }
        System.out.println("Operation done successfully");
    }

}


